﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SiteNavigation.Services;
using SiteNavigation.Entities;
using Microsoft.Extensions.Logging;
using SiteNavigation.Models;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SiteNavigation.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SitesController : ControllerBase
    {
        private readonly ISiteManageService _service;
        private readonly ILogger _logger;
        public SitesController(ISiteManageService siteManageService, ILogger<SitesController> logger)
        {
            _service = siteManageService;
            _logger = logger;
        }

        // GET: api/<SitesController>
        [HttpGet]
        public async Task<ActionResult> Get()
        {
            try
            {
                var sites = await _service.GetAllAsync();
                return new JsonResult(ResponseViewModel.Success(sites));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取站点列表失败");
                return new JsonResult(ResponseViewModel.Fail(ex, "获取站点列表失败"));
            }
        }

        // GET api/<SitesController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult> Get(int id)
        {
            try
            {
                var site = await _service.GetByIdAsync(id);
                return new JsonResult(ResponseViewModel.Success(site));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取站点信息失败");
                return new JsonResult(ResponseViewModel.Fail(ex, "获取站点信息失败"));
            }
        }

        // POST api/<SitesController>
        [HttpPost]
        public async Task<ActionResult> Post([FromBody]SiteEntity entity)
        {
            try
            {
                await _service.SaveAsync(entity);
                return new JsonResult(ResponseViewModel.Success("保存站点信息成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存站点信息失败");
                return new JsonResult(ResponseViewModel.Fail(ex, "保存站点信息失败"));
            }
        }

        // DELETE api/<SitesController>/delete/5
        [HttpPost("[action]/{id}")]
        public async Task<ActionResult> Delete(int id)
        {
            try
            {
                await _service.RemoveByIdAsync(id);
                return new JsonResult(ResponseViewModel.Success("删除站点信息成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除站点信息失败");
                return new JsonResult(ResponseViewModel.Fail("删除站点信息失败"));
            }
        }
    }
}
